<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'
import type { EChartsOption } from 'echarts'

interface Dataset {
  label: string
  data: number[]
  borderColor: string
}

interface ChartData {
  labels: string[]
  datasets: Dataset[]
}

const props = defineProps<{
  chartData: ChartData
}>()

const chartRef = ref<HTMLElement>()
let chart: echarts.ECharts | null = null

const initChart = () => {
  if (!chartRef.value) return
  
  chart = echarts.init(chartRef.value)
  updateChart()
}

const updateChart = () => {
  if (!chart) return

  const series = props.chartData.datasets.map(dataset => ({
    name: dataset.label,
    type: 'line',
    smooth: true,
    data: dataset.data,
    itemStyle: {
      color: dataset.borderColor
    },
    lineStyle: {
      color: dataset.borderColor
    },
    areaStyle: {
      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        {
          offset: 0,
          color: dataset.borderColor + '40' // 40 is hex for 25% opacity
        },
        {
          offset: 1,
          color: dataset.borderColor + '00' // 00 is hex for 0% opacity
        }
      ])
    }
  }))

  const option: EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'line'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: props.chartData.labels,
      axisLine: {
        lineStyle: {
          color: '#e5e7eb'
        }
      },
      axisLabel: {
        color: '#6b7280'
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: '#e5e7eb',
          type: 'dashed'
        }
      },
      axisLabel: {
        color: '#6b7280',
        formatter: (value: number) => {
          return '¥' + value.toLocaleString()
        }
      }
    },
    series
  }

  chart.setOption(option)
}

watch(() => props.chartData, updateChart, { deep: true })

onMounted(() => {
  initChart()
  window.addEventListener('resize', () => chart?.resize())
})

onUnmounted(() => {
  chart?.dispose()
  window.removeEventListener('resize', () => chart?.resize())
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style> 